package com.health.trans.util;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;

import javax.persistence.Id;
import javax.persistence.Table;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
@Slf4j
public class ReflectKit {

    private static final List<String> baseRegisterStr = Arrays.asList("cardType", "cardNum");

    public static String getTableName(Class<?> targetClass) {
        Table table = targetClass.getAnnotation(Table.class);
        return Objects.isNull(table) ? "" : table.name();
    }

    /**
     * 获取 子表 ES 中数据 key
     *
     * @param obj
     * @return
     */
    public static String getEsKeyByChildIdStr(Object obj) {

        Table table= obj.getClass().getAnnotation(Table.class);

        Field[] fields=obj.getClass().getDeclaredFields();

        String id="";



        for (int i = 0; i < fields.length; i++) {

            Field field=fields[i];
            if(!field.isAccessible()){
                field.setAccessible(true);
            }

            //获取主键信息
            Id entityId=field.getAnnotation(Id.class);
            if(null!=entityId){
                try {
                    if(!"tb_base_register".equals(table.name())){
                        id+="_"+field.get(obj).toString();
                    }else if(!"cardType".equals(field.getName())&&!"cardNum".equals(field.getName())){
                        id+="_"+field.get(obj).toString();
                    }
                } catch (IllegalAccessException e) {
                    log.error("获取主键错误",e);
                }
            }

        }
        if(StrUtil.isNotBlank(id)){
            id=table.name()+id;
        }

        return id;
    }

}
